var _INDEX = '0';
var _TYPE = 'MerchantWords:Search Keyword';

function log(msg,level = config.LOG._LOG_LEVEL_DEBUG) {
    logger.out(`{${_TYPE} (index:${_INDEX})} ` + msg,level)
}

function parser() {
    let result = {
        rows :{
            amazonSearchList:[],
            basisInfo:{},
            total:0,
            page:0
        },
        code:Const._RETCODE_HANDLER_FAILED
    };

    let maxPage = getMaxPage();
    // if(!maxPage){
    //     return result;
    // }
    log(`MaxPage:${maxPage}`);
    result.rows.total = maxPage;
    result.rows.page = getCurrentPage();
    result.rows.basisInfo = basisInfo();

    let tableList = $('#resultsTable > tbody > tr');
    log(`Length:${tableList.length}`);

    for (let i = 0; i< tableList.length; i++){
        let dom = tableList[i];
        let names = parserNames(dom); //关键字列表
        let keywordId = analyzeKeywordId(dom); //关键字搜索analyze调用时需要的加密字符串
        result.rows.amazonSearchList.push({
            names:names,
            keywordId:keywordId,
            searchTrends:searchTrends(dom),
            searchVolume:searchVolume(dom),
            threeAvg:threeAvg(dom),
            twelveAvg:twelveAvg(dom),
            depth:depth(dom),
            results:results(dom),
            reviews:reviews(dom),
            appearance:appearance(dom),
            lastSeen:lastSeen(dom),
            dominateCategories:dominateCategories(dom)
        })

    }
    if(result.rows.amazonSearchList && result.rows.amazonSearchList.length > 0){
        result.code = Const._RETCODE_SUCCESS;
    }
    return result;
}

/**
 * 获取最大页
 */
function getMaxPage() {
    let doms = $('body > div.wrapper.wrapper--alt > section > div.container__section > div.section__actions > nav > ul > li')
    let length = doms.length;
    if(length < 2){
        return 1;
    }
    let page = $(doms[length - 2]).find('a').text();
    return utils.special(page);
}

/**
 * 获取当前页
 */
function getCurrentPage() {
    // let dom = $('body > div.wrapper.wrapper--alt > section > div.container__section > div.section__actions > nav > ul > li.active.disabled');
    // return utils.special($(dom).text());
    return 0;
}

function basisInfo() {
    let doms = $('body > div.wrapper.wrapper--alt > section > div.container > header > div > div > div:nth-child(2) > div > div > table > tbody > tr > td');
    let searchVolume = $(doms[0]).text();
    if(!searchVolume || searchVolume === ''){
        //兼容不同页面规则
        doms = $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > table > tbody > tr > td');
    }
    searchVolume = $(doms[0]).text();
    let depth = $(doms[1]).text();
    let appearance = $(doms[2]).text();
    let categories = $(doms[3]).find('small').text();
    return {
        searchVolume:searchVolume,
        depth:depth,
        appearance:appearance,
        categories:categories
    }
}

function parserNames(dom) {
    let aList = $(dom).find('td.table__col-size9 > div > div > div > ul > li.keywords > span > a');
    if(!aList || aList.length === 0){
        return [];
    }
    let result = [];
    for(let i = 0; i < aList.length; i++){
        let name = $(aList[i]).text();
        name = utils.special(name);
        name = name.trim();
        let url = $(aList[i]).attr('href');
        result.push({
            name:name, //关键字名称
            url:`https://www.merchantwords.com${url}` //跳转地址
        });
    }
    return result;
}

/**
 * 解析keywordId
 */
function analyzeKeywordId(dom) {
    let adom = $(dom).find('td.table__col-size9 > div > div > div > ul > li:nth-child(3) > a');
    return $(adom).attr('data-keywordid')
}

function searchTrends(dom) {
    let adom = $(dom).find('td:nth-child(2)');
    return $(adom).text();
}

/**
 * SEARCH VOLUME
 */
function searchVolume(dom) {
    let adom = $(dom).find('td:nth-child(3)');
    return $(adom).text();
}

/**
 * 3M AVG
 */
function threeAvg(dom) {
    let adom = $(dom).find('td:nth-child(4)');
    return $(adom).text();
}

/**
 * 12M AVG
 */
function twelveAvg(dom) {
    let adom = $(dom).find('td:nth-child(5)');
    return $(adom).text();
}

/**
 * DEPTH
 */
function depth(dom) {
    let adom = $(dom).find('td:nth-child(6)');
    return $(adom).text();
}

/**
 * RESULTS
 */
function results(dom) {
    let adom = $(dom).find('td:nth-child(7)');
    return $(adom).text();
}

/**
 * PAGE 1 REVIEWS
 */
function reviews(dom) {
    let adom = $(dom).find('td:nth-child(8)');
    return $(adom).text();
}

/**
 * APPEARANCE
 */
function appearance(dom) {
    let adom = $(dom).find('td:nth-child(9)');
    return $(adom).text();
}

/**
 * LAST SEEN
 */
function lastSeen(dom) {
    let adom = $(dom).find('td:nth-child(10)');
    return $(adom).text();
}

/**
 * DOMINANT CATEGORIES
 */
function dominateCategories(dom) {
    let adom = $(dom).find('td:nth-child(11) > small');
    return $(adom).text();
}

try {
    var $ = cheerio.load(htmlString);
    result = parser();
    parserInfo.index = _INDEX;
    parserInfo.type = _TYPE;
} catch (e) {
    log(`Parsing Exception:${e.message}`,config.LOG._LOG_LEVEL_ERROR);
    result.code = Const._RETCODE_HANDLER_FAILED;
}

